<template>
  <div class="top-right-btn" :style="style">
    <div class="btn-group">
      <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top" v-if="search">
        <el-button size="small" @click="toggleSearch()">
          <el-icon><Search /></el-icon>
        </el-button>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="刷新" placement="top">
        <el-button size="small" @click="refresh()">
          <el-icon><Refresh /></el-icon>
        </el-button>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="显隐列" placement="top" v-if="Object.keys(columns).length > 0">
        <el-button size="small" @click="showColumn()" v-if="showColumnsType == 'transfer'">
          <el-icon><Operation /></el-icon>
        </el-button>
        <el-dropdown trigger="click" :hide-on-click="false" style="padding-left: 12px" v-if="showColumnsType == 'checkbox'">
          <el-button size="small">
            <el-icon><Operation /></el-icon>
          </el-button>
          <template #dropdown>
            <!-- 全选/反选 按钮 -->
            <el-dropdown-item>
              <el-checkbox :indeterminate="isIndeterminate" v-model="isChecked" @change="toggleCheckAll"> 列展示 </el-checkbox>
            </el-dropdown-item>
            <div class="check-line"></div>
            <template v-for="(item, key) in columns" :key="key">
              <el-dropdown-item>
                <el-checkbox v-model="item.visible" @change="checkboxChange($event, key)" :label="item.label" />
              </el-dropdown-item>
            </template>
          </template>
        </el-dropdown>
      </el-tooltip>
    </div>
    <el-dialog :title="title" v-model="open" append-to-body>
      <el-transfer
        :titles="['显示', '隐藏']"
        v-model="value"
        :data="transferData"
        @change="dataChange"
      ></el-transfer>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { Search, Refresh, Operation } from '@element-plus/icons-vue';

interface ColumnItem {
  label: string;
  visible: boolean;
  key?: string;
}

interface Props {
  /* 是否显示检索条件 */
  showSearch?: boolean;
  /* 显隐列信息（数组格式、对象格式） */
  columns?: ColumnItem[] | Record<string, ColumnItem>;
  /* 是否显示检索图标 */
  search?: boolean;
  /* 显隐列类型（transfer穿梭框、checkbox复选框） */
  showColumnsType?: string;
  /* 右外边距 */
  gutter?: number;
}

const props = withDefaults(defineProps<Props>(), {
  showSearch: true,
  columns: () => ({}),
  search: true,
  showColumnsType: 'checkbox',
  gutter: 10,
});

const emit = defineEmits<{
  'update:showSearch': [value: boolean];
  'queryTable': [];
}>();

// 显隐数据
const value = ref<number[]>([]);
// 弹出层标题
const title = ref('显示/隐藏');
// 是否显示弹出层
const open = ref(false);

const style = computed(() => {
  const ret: Record<string, string> = {};
  if (props.gutter) {
    ret.marginRight = `${props.gutter / 2}px`;
  }
  return ret;
});

const isChecked = computed({
  get() {
    return Array.isArray(props.columns) 
      ? props.columns.every((col) => col.visible) 
      : Object.values(props.columns).every((col) => col.visible);
  },
  set() {}
});

const isIndeterminate = computed(() => {
  return Array.isArray(props.columns) 
    ? props.columns.some((col) => col.visible) && !isChecked.value
    : Object.values(props.columns).some((col) => col.visible) && !isChecked.value;
});

const transferData = computed(() => {
  if (Array.isArray(props.columns)) {
    return props.columns.map((item, index) => ({ key: index, label: item.label }));
  } else {
    return Object.keys(props.columns).map((key, index) => ({ key: index, label: props.columns[key].label }));
  }
});

// 搜索
const toggleSearch = () => {
  emit('update:showSearch', !props.showSearch);
};

// 刷新
const refresh = () => {
  emit('queryTable');
};

// 右侧列表元素变化
const dataChange = (data: number[]) => {
  if (Array.isArray(props.columns)) {
    for (let item in props.columns) {
      const key = props.columns[item].key;
      if (key !== undefined) {
        props.columns[item].visible = !data.includes(parseInt(key));
      }
    }
  } else {
    Object.keys(props.columns).forEach((key, index) => {
      props.columns[key].visible = !data.includes(index);
    });
  }
};

// 打开显隐列dialog
const showColumn = () => {
  open.value = true;
};

// 单勾选
const checkboxChange = (event: boolean, key: string) => {
  if (Array.isArray(props.columns)) {
    const item = props.columns.filter(item => item.key == key)[0];
    if (item) {
      item.visible = event;
    }
  } else {
    props.columns[key].visible = event;
  }
};

// 切换全选/反选
const toggleCheckAll = () => {
  const newValue = !isChecked.value;
  if (Array.isArray(props.columns)) {
    props.columns.forEach((col) => (col.visible = newValue));
  } else {
    Object.values(props.columns).forEach((col) => (col.visible = newValue));
  }
};

// 初始化
// transfer穿梭显隐列初始默认隐藏列
if (Array.isArray(props.columns)) {
  for (let item in props.columns) {
    if (props.columns[item].visible === false) {
      value.value.push(parseInt(item));
    }
  }
} else {
  Object.keys(props.columns).forEach((key, index) => {
    if (props.columns[key].visible === false) {
      value.value.push(index);
    }
  });
}
</script>

<style lang="scss" scoped>
:deep(.el-transfer__button) {
  border-radius: 50%;
  padding: 12px;
  display: block;
  margin-left: 0px;
}

:deep(.el-transfer__button:first-child) {
  margin-bottom: 10px;
}

.check-line {
  height: 1px;
  background-color: #e4e7ed;
  margin: 8px 0;
}

.top-right-btn {
  .btn-group {
    display: flex;
    gap: 4px;
    justify-content: flex-end;
  }
  
  .item {
    margin: 0;
  }
}
</style>
